package com.yksj.healthtalk.ui.views;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.DoctorNavigationPopAdapter;
import com.yksj.healthtalk.adapter.DoctorProPopAdapter;
import com.yksj.healthtalk.db.DictionaryHelper;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.doctor.DoctorNavigationLisenter;

/**
 * 医生上面的导航
 * 
 * @author Administrator
 * 
 */
public class DoctorNavigationBar extends LinearLayout implements
		OnClickListener, OnItemClickListener {
	private Context context;
	private LinearLayout mBarLinearLayout;
	private int[] ServiceIds = new int[] { 1, 2 };
	private int[] ConditionIds = new int[] { 3, 4, 5, 6 };
	private PopupWindow window;
	private View mNavigationBottomLine;
	private DoctorNavigationPopAdapter adapter;
	private DoctorProPopAdapter mDoctorProPopAdapter; // 省适配器
	private ListView mProvinceListView;
	private LinearLayout mPopInputLinearLayout;
	private ListView mListView;
	private HashMap<String, List<Map<String, String>>> cityMap;
//	private LinkedHashMap<String, String> keshiData;
	private LinkedHashMap<String, String> titles;;
	private List<Map<String, String>> proList;
	// private int mProvinceId = -1; // 省 code
	private LinkedHashMap<String, String> linkedHashMap; // 通用适配器集合
	private Button mInputSureBtn; // 医院确定按钮
	private EditText mInputEt;
	private LinearLayout mListLin;// 输入医院的线性布局
	private DictionaryHelper dictionaryHelper;
	private DoctorNavigationLisenter mDoctorNavigationLisenter;
	private HashMap<Integer, String> saveTitleNameMap;
	private String mProvinceName;
	private boolean isHide=false;//是否隐藏 医生 和 科室
	public DoctorNavigationBar(Context context) {
		super(context);
		init(context);
	}

	public DoctorNavigationBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private void init(Context context) {
		this.context = context;
		saveTitleNameMap = new HashMap<Integer, String>();
		linkedHashMap = new LinkedHashMap<String, String>();
		dictionaryHelper = DictionaryHelper.getInstance(context);
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.doctor_navigation_bar, this);
		mBarLinearLayout = (LinearLayout) findViewById(R.id.bar_lin);
		mNavigationBottomLine = findViewById(R.id.navigation_bottom_lin);
		findViewById(R.id.find_by_service_btn).setOnClickListener(this);
		findViewById(R.id.find_by_conditon_btn).setOnClickListener(this);
		initCondition(context);
		if (cityMap == null) {
			queryCity();
		}
		if (titles == null) {
			queryDepartments();
		}
	}

	public void setDoctorNavigationLisenter(DoctorNavigationLisenter lisenter) {
		this.mDoctorNavigationLisenter = lisenter;

	}

	public void initService(Context context) {
		mBarLinearLayout.removeAllViews();
		String str[] = new String[] { "选择服务", "是否收费" };
		for (int i = 0; i < str.length; i++) {
			DoctorNavigationBarItem barItem = new DoctorNavigationBarItem(
					context);
			barItem.setTextView(str[i]);
			barItem.setWeightSum(1);
			barItem.setLayoutParams(new LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT, 1));
			barItem.setId(ServiceIds[i]);
			if (saveTitleNameMap.containsKey(ServiceIds[i])
					&& adapter.getAllSelect().containsKey(ServiceIds[i])) {
				barItem.setTextView(saveTitleNameMap.get(ServiceIds[i]));
			}
			barItem.setOnClickListener(this);
			mBarLinearLayout.addView(barItem);
		}
	}

	public void initCondition(Context context) {
		mBarLinearLayout.removeAllViews();
		String str[] = new String[] { "地区", "医院", "科室", "职称" };
		for (int i = 0; i < str.length; i++) {
			DoctorNavigationBarItem barItem = new DoctorNavigationBarItem(
					context);
			barItem.setTextView(str[i]);
			barItem.setLayoutParams(new LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT, 1));
			barItem.setWeightSum(1);
			barItem.setId(ConditionIds[i]);
//			if (i==2) {//暂时移除科室
//				barItem.setVisibility(View.GONE);
//			}
			if (saveTitleNameMap.containsKey(ConditionIds[i])
					&& adapter.getAllSelect().containsKey(ConditionIds[i])) {
				// 医院为""
				if (!saveTitleNameMap.get(ConditionIds[i]).equals("")) {
					barItem.setTextView(saveTitleNameMap.get(ConditionIds[i]));
				}
			}
			barItem.setOnClickListener(this);
			mBarLinearLayout.addView(barItem);
		}
		//如果是从多美医生过来的  就隐藏医院 和 科室 选项
		if(isHide){
			findViewById(4).setVisibility(View.GONE);//医生
			findViewById(5).setVisibility(View.GONE);//科室
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.find_by_service_btn:
			initService(context);
			break;
		case R.id.find_by_conditon_btn:
			initCondition(context);
			break;
		case 1:// 选择服务
				// choiceService(v);
			if (mDoctorNavigationLisenter != null) {
				mDoctorNavigationLisenter.OnSelectService(v);
			}
			break;
		case 2:// 是否收费
			choicecharge(v);
			break;
		case 3:// 地区
			choiceCity(v);
			break;
		case 4:// 医院
			choiceHospital(v);
			break;
		case 5:// 科室
//			choiceDepartment(v);
			if (mDoctorNavigationLisenter != null) {
				mDoctorNavigationLisenter.OnDcotorDepartments(v);
			}
			break;
		case 6:// 职称
			choiceTitles(v);
			break;
		case R.id.input_sure_btn:
			if (window.isShowing()) {
				window.dismiss();
			}
			if (mDoctorNavigationLisenter != null) {
				adapter.setSelect(mInputEt.getText().toString().trim(),adapter.getClickBtnId());
				mDoctorNavigationLisenter.OnHttpGetDoctorListForNavigation(adapter.getAllSelect(), adapter.getClickIdCodeMap(), mInputEt.getText().toString().trim(), 4);
				saveTitleNameMap.put(4, mInputEt.getText().toString().trim());
				// 显示标题
				DoctorNavigationBarItem ad = (DoctorNavigationBarItem) mBarLinearLayout
						.findViewById(4);
				if (mInputEt.getText().toString().trim().equals("")
						|| mInputEt.getText().toString().trim().equals("全部")) {
					ad.setTextView("医院");
				} else {
					ad.setTextView(mInputEt.getText().toString().trim());
				}

			}
			break;
		default:
			break;
		}
	}

	// 职称
	private void choiceTitles(View v) {
		// TODO Auto-generated method stub
		showPopWindow(context, v, false, false);
		((DoctorNavigationBarItem) v).startRotateAnimation(90);
		linkedHashMap.clear();
		linkedHashMap.putAll(titles);
		changeData(v, linkedHashMap);
	}

//	// 科室
//	private void choiceDepartment(View v) {
//		showPopWindow(context, v, false, false);
//		((DoctorNavigationBarItem) v).startRotateAnimation(90);
//		linkedHashMap.clear();
//		linkedHashMap.putAll(keshiData);
//		changeData(v, linkedHashMap);
//	}

	private void choiceHospital(View v) {
		showPopWindow(context, v, false, true);
		// 判断是否以前请求数据
		adapter.setClickBtnId(4);
		if (adapter.getAllSelect().containsKey(4)) {
			String str = adapter.getAllSelect().get(4);
			mInputEt.setText(str);
		} else {
			mInputEt.setText("");
		}
		linkedHashMap.clear();
		((DoctorNavigationBarItem) v).startRotateAnimation(90);
		Timer timer = new Timer();
	     timer.schedule(new TimerTask()
	     {
	          
	         public void run()
	         {
	             InputMethodManager inputManager =
	                 (InputMethodManager)mInputEt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
	             inputManager.showSoftInput(mInputEt, 0);
	         }
	     },
	         250);
	}

	// 选择城市
	private void choiceCity(View v) {
		showPopWindow(context, v, true, false);
		((DoctorNavigationBarItem) v).startRotateAnimation(90);
		// 全部 初始化右边
		if (mProvinceListView.getTag() == null) {
			linkedHashMap = new LinkedHashMap<String, String>();
			linkedHashMap.put("全部", "0");
			// adapter.setClickBtnId(0, linkedHashMap);
			adapter.setClickBtnId(3, linkedHashMap);
			adapter.notifyDataSetChanged();
		} else if (!adapter.getAllSelect().containsKey(3)) {
			linkedHashMap = new LinkedHashMap<String, String>();
			linkedHashMap.put("全部", "0");
			// adapter.setClickBtnId(0, linkedHashMap);
			adapter.setClickBtnId(3, linkedHashMap);
			mDoctorProPopAdapter.setSelectPosition(-1);
			mDoctorProPopAdapter.notifyDataSetChanged();
			adapter.notifyDataSetChanged();
		} else {
			List<Map<String, String>> list = cityMap.get(proList
					.get((Integer) mProvinceListView.getTag()).get("name")
					.toString());
			LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
			for (int i = 0; i < list.size(); i++) {
				map.put(list.get(i).get("name"), list.get(i).get("code"));

				// adapter.setClickBtnId(mProvinceId, map);
				mDoctorProPopAdapter
						.setSelectPosition((Integer) mProvinceListView.getTag());
				adapter.setClickProvincePosition(
						(Integer) mProvinceListView.getTag(), mProvinceListView);
				adapter.setClickBtnId(3, map);
				adapter.notifyDataSetChanged();
			}
		}

	}

	/**
	 * 是否收费
	 * 
	 * @param v
	 */
	private void choicecharge(View v) {
		showPopWindow(context, v, false, false);
		((DoctorNavigationBarItem) v).startRotateAnimation(90);
		linkedHashMap = new LinkedHashMap<String, String>();
		linkedHashMap.put("全部", "2");
		linkedHashMap.put("收费", "1");
		linkedHashMap.put("免费", "0");
		changeData(v, linkedHashMap);
	}

	/**
	 * 搜索服务类型
	 * @param v
	 */
	public void choiceService(View v, ArrayList<HashMap<String, String>> list) {
		showPopWindow(context, v, false, false);
		((DoctorNavigationBarItem) v).startRotateAnimation(90);
		linkedHashMap = new LinkedHashMap<String, String>();
		for (HashMap<String, String> map : list) {
			linkedHashMap.put(map.get("SERVICE_TYPE"),String.valueOf(map.get("SERVICE_TYPE_ID")));
		}
		changeData(v, linkedHashMap);
	}
	
	
	/**
	 * 搜索科室名称
	 * @param v
	 */
	public void choiceDcotorDepartments(View v, ArrayList<HashMap<String, String>> list) {
		showPopWindow(context, v, false, false);
		((DoctorNavigationBarItem) v).startRotateAnimation(90);
		linkedHashMap = new LinkedHashMap<String, String>();
		for (HashMap<String, String> map : list) {
			linkedHashMap.put(map.get("SERVICE_TYPE"),String.valueOf(map.get("SERVICE_TYPE_ID")));
		}
		changeData(v, linkedHashMap);
	}

	/**
	 * 
	 * @param context
	 * @param view
	 *            popview
	 * @param animaView
	 *            动画的view
	 * @return
	 */
	public PopupWindow showPopWindow(Context context, final View animaView,
			Boolean isDoubleList, Boolean isEditView) {
		if (window == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(context.LAYOUT_INFLATER_SERVICE);
			View v = inflater.inflate(R.layout.popwindow_doctor_main, null);
			mListView = (ListView) v.findViewById(R.id.pop_list);
			mListLin = (LinearLayout) v.findViewById(R.id.list_lin);
			mProvinceListView = (ListView) v.findViewById(R.id.province_list);
			mPopInputLinearLayout = (LinearLayout) v
					.findViewById(R.id.pop_input_lin);
			mInputSureBtn = (Button) v.findViewById(R.id.input_sure_btn);
			mInputEt = (EditText) v.findViewById(R.id.input_et);
			mInputSureBtn.setOnClickListener(this);
			window = new PopupWindow(v, ViewGroup.LayoutParams.FILL_PARENT, 200);
			adapter = new DoctorNavigationPopAdapter(context, mInputEt);
			mListView.addFooterView(inflater.inflate(R.layout.list_line_layout, null));
			mListView.setAdapter(adapter);
			mListView.setOnItemClickListener(this);
			mDoctorProPopAdapter = new DoctorProPopAdapter(context, proList);
			mProvinceListView.setAdapter(mDoctorProPopAdapter);
			mProvinceListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					if (view.getTag() != null&& view.getTag() instanceof Integer) {
						mDoctorProPopAdapter.setSelectPosition(position);
						mDoctorProPopAdapter.notifyDataSetChanged();
						// mProvinceId = (Integer) view.getTag();
						mProvinceName = ((TextView) view).getText().toString();
						List<Map<String, String>> list = cityMap.get(((TextView) view).getText().toString());
						LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
						for (int i = 0; i < list.size(); i++) {
							map.put(list.get(i).get("name"),list.get(i).get("code"));
						}
						// adapter.setClickBtnId(mProvinceId, map);
						linkedHashMap.clear();
						linkedHashMap.putAll(map);
						adapter.setClickProvincePosition(position,mProvinceListView);
						adapter.setClickBtnId(3, linkedHashMap);
						adapter.notifyDataSetChanged();
					}
					;
				}
			});
		}
		// 控件的显示与否
		if (isDoubleList) {
			window.setHeight(500);
			mListLin.setVisibility(View.VISIBLE);
			mProvinceListView.setVisibility(View.VISIBLE);
			mPopInputLinearLayout.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
		} else if (isEditView) {// 是否是医院的输入框
			window.setHeight(150);
			mListLin.setVisibility(View.GONE);
			mProvinceListView.setVisibility(View.GONE);
			mPopInputLinearLayout.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
		} else {
			window.setHeight(500);
			mListLin.setVisibility(View.VISIBLE);
			mProvinceListView.setVisibility(View.GONE);
			mPopInputLinearLayout.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
		}
		window.setTouchable(true);
		window.setFocusable(true);
		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
		window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		window.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
		window.showAsDropDown(mNavigationBottomLine);
		window.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				// TODO Auto-generated method stub
				((DoctorNavigationBarItem) animaView).startRotateAnimation(0);
			}
		});
		return window;
	}

	/**
	 * 改变数据
	 * 
	 * @param v
	 * @param linkedHashMap
	 */
	private void changeData(View v, LinkedHashMap<String, String> linkedHashMap) {
		adapter.setClickBtnId(v.getId(), linkedHashMap);
		adapter.notifyDataSetChanged();
	}

	// 查询科室
	private void queryDepartments() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				titles = new LinkedHashMap<String, String>();
				titles.put(context.getString(R.string.limit_no), "0");
				LinkedHashMap<String, String> list = DictionaryHelper
						.getInstance(context).querydoctorTitles(context);
				list.remove("不详");
				titles.putAll(list);
				titles.remove("未知");
			}
		}).start();
	}

	// 查询地区
	private void queryCity() {
		cityMap = new HashMap<String, List<Map<String, String>>>();
		proList = DictionaryHelper.getInstance(context).setCityData(context,
				cityMap);
		// 每项加个全部
		for (Map<String, String> map : proList) {
			HashMap<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("name", context.getString(R.string.limit_no));
			hashMap.put("code", map.get("code"));
			String name = map.get("name");
			cityMap.get(name).add(0, hashMap);
		}
		HashMap<String, String> hashMap = new HashMap<String, String>();
		hashMap.put("name", context.getString(R.string.limit_no));
		hashMap.put("code", "0");
		proList.add(0, hashMap);
		
//		HashMap<String, String> addhashMap = new HashMap<String, String>();
//		addhashMap.put("name", "USA");
//		addhashMap.put("code", "690000");
//		proList.add(proList.size(),addhashMap);
		
		List<Map<String, String>> arr = new ArrayList<Map<String, String>>();
		arr.add(hashMap);
		cityMap.put(context.getString(R.string.limit_no), arr);
		
//		arr.clear();
//		arr.add(addhashMap);
//		cityMap.put("USA", arr);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// ClickBtnId
		if (mDoctorNavigationLisenter != null) {
			if (adapter.getClickBtnId() == 3) {
				mProvinceListView.setTag(mDoctorProPopAdapter.getSelectPosition());
			}
			adapter.setSelect(position + "", adapter.getClickBtnId());
			mDoctorNavigationLisenter.OnHttpGetDoctorListForNavigation(adapter.getAllSelect(), adapter.getClickIdCodeMap(), position + "",adapter.getClickBtnId());
		}
		if (window.isShowing()) {
			window.dismiss();
		}

		// 改变标题栏的字
		DoctorNavigationBarItem ad = (DoctorNavigationBarItem) mBarLinearLayout
				.findViewById(adapter.getClickBtnId());
		ArrayList<String> list = new ArrayList<String>(linkedHashMap.keySet());
		if (!list.get(position).equals("全部")) {
			ad.setTextView(list.get(position));
		} else {
			switch (adapter.getClickBtnId()) {
			case 1:
				ad.setTextView("选择服务");
				break;
			case 2:
				ad.setTextView("是否收费");
				break;
			case 3://显示省名
				if (!TextUtils.isEmpty(mProvinceName)) {
					ad.setTextView(mProvinceName);
				}
				break;
			case 4:
				ad.setTextView("医院");
				break;
			case 5:
				ad.setTextView("科室");
				break;
			case 6:
				ad.setTextView("职称");
				break;

			default:
				break;
			}
		}
		saveTitleNameMap.put(adapter.getClickBtnId(), ad.getTextName());

	}

	public void setHidenView() {
		isHide=true;
		initCondition(context);
	}

}
